package cn.demomaster.quicklogger.writer;

import java.io.File;
import java.io.IOException;

import static cn.demomaster.quicklogger.util.FileUtil.createFile;

public class MapBufferWriter implements LoggerWriter {


    //缓存触发扩容最大值
    private static long fileSize = 10 * 1024;
    private static MappedByteBufferHelper.MyMappedByteBuffer mapByteBuffer;

    public static void setFileSize(long size) {
        fileSize = size;
    }

    //写入日志数据
    @Override
    public void writeLog(String logFilePath, byte[] bytes) {
        //先判断文件是否存在，不存在则创建
        File file = new File(logFilePath);
        if (!file.exists()) {
            try {
                createFile(file);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            if (mapByteBuffer != null) {
                mapByteBuffer.close();
                mapByteBuffer = null;
            }
        }
        if (mapByteBuffer == null) {//虚拟内存映射
            try {
                mapByteBuffer = MappedByteBufferHelper.map_log(file, fileSize);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        if (mapByteBuffer != null) {//确保映射成功，可以写入
            try {
                mapByteBuffer.put(bytes==null ? "NUL".getBytes() : bytes);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

}
